import { URL } from "url";
import utils from "../utils";
import networkutil from "../utils/network";
import { Blob } from "buffer";
import fileservice from "./fileservice";

const createOrUpdateArticle = (articleInfo:{
    userid:string,
    title:string,
    description:string,
    content?:string,
    isDraft:boolean,
    tag?:string,
    articleid?:string,
    url?:string
})=>{
    //TODO: replace this with fileservice, 
    var arr = [articleInfo.content||""];
    var title = articleInfo.title;
    if(title && !title.endsWith(".html")){
        title = title + ".html";
    }
    var file = new File(arr,title);
   return fileservice.uploadFile(file,'blogs').then((resp:any)=>{
        console.debug("upload file result:"+JSON.stringify(resp));
        delete articleInfo.content
        console.debug("blog url:"+resp.content.fileurl)
        var url = "/blog/create";
        if(!utils.str.isNullOrEmpty(articleInfo.url)){
            url = "/blog/update";
        }
        return networkutil.post(url,{params:{
            ...articleInfo,
            url:resp?.content?.fileurl||""
           }})
            .then((resp)=>{
                return Promise.resolve(true);
        })
    });
//    return networkutil.post("/files/uploadPost",{headers:{ 
//             "Content-Type":"text/html",
//             userid:articleInfo.userid||"unknown",
//             url:articleInfo.url
//         },params:articleInfo.content}).then((resp:any)=>{
        
//         console.debug("upload file result:"+JSON.stringify(resp));
//         delete articleInfo.content
//         console.debug("blog url:"+resp.content.url)
//         var url = "/blog/create";
//         if(!utils.str.isNullOrEmpty(articleInfo.url)){
//             url = "/blog/update";
//         }
//         return networkutil.post(url,{params:{
//             ...articleInfo,
//             url:resp?.content?.url||""
//            }})
//             .then((resp)=>{
//                 return Promise.resolve(true);
//         })
//     })
   
}

const loadArticles = (userid:string="")=> {
    return networkutil.get("/blog/list",{queries:{userid}})
}

const removeArticles = (userid:string="unknown",articles:Array<string>)=>{
    return networkutil.delete("/blog",{params:{
        userid,
        articles:articles
    }})
}



export default {
    createOrUpdateArticle,
    loadArticles,
    removeArticles
}